package com.zscat.mallplus.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zscat.mallplus.cms.entity.CmsSubject;
import com.zscat.mallplus.cms.entity.CmsSubjectComment;
import com.zscat.mallplus.cms.mapper.CmsSubjectCommentMapper;
import com.zscat.mallplus.cms.service.ICmsSubjectCommentService;
import com.zscat.mallplus.cms.service.ICmsSubjectService;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.utils.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 专题评论表 服务实现类
 * </p>
 *
 * @author zscat
 * @since 2019-04-17
 */
@Slf4j
@Service
public class CmsSubjectCommentServiceImpl extends ServiceImpl<CmsSubjectCommentMapper, CmsSubjectComment> implements ICmsSubjectCommentService {

    @Resource
    private CmsSubjectCommentMapper subjectCommentMapper;

    @Resource
    private IUmsMemberService memberService;

    @Resource
    private ICmsSubjectService subjectService;

    /**
     * 保存文章评论
     *
     * @param subjectComment
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public Object saveSubjectComment(CmsSubjectComment subjectComment) {
        try {
            UmsMember currentMember = memberService.getNewCurrentMember();
            if (null != currentMember) {
                subjectComment.setMemberId(currentMember.getId());
                subjectComment.setMemberNickName(currentMember.getNickname());
                subjectComment.setMemberIcon(currentMember.getIcon());
            } else {
                return new CommonResult().failed("请先登录");
            }

            subjectComment.setCreateTime(new Date());
            subjectComment.setShowStatus(0);
            subjectCommentMapper.insert(subjectComment);
            // 根据文章ID查询评论量
            int commentCount = subjectService.getById(subjectComment.getSubjectId()).getCommentCount();
            CmsSubject subject = new CmsSubject();
            subject.setCommentCount(commentCount + 1);
            subjectService.update(subject, new QueryWrapper<CmsSubject>().eq("id", subjectComment.getSubjectId()));
            return new CommonResult().success("评论成功");
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
    }
}
